﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using LynxWebLog.Areas.Blogs.ViewModels;

namespace LynxWebLog.Areas.Blogs.Controllers
{
    public class PostCategoryController : Controller
    {
        private string _blogOwner;
        private string _blogName;
        private BlogSupport blogSupport;
        private HttpClient client;
        protected override void Initialize(RequestContext requestContext)
        {
            ViewBag.Version = " v: " + Assembly.GetExecutingAssembly().GetName().Version;
            ViewBag.CategoryDisplay = false;
            ViewBag.GoogleAdDisplay = false;
            base.Initialize(requestContext);
            this._blogOwner = this.ControllerContext.RouteData.Values["username"].ToString();
            this._blogName = this.ControllerContext.RouteData.Values["blogname"].ToString();
            ViewBag.LegacyBrowser = Request.UserAgent.Contains("iPad; CPU OS 5");
            this.blogSupport = new BlogSupport();
            client = ClientUtility.BlogAPIClient();
        }

        //
        // GET: /Blogs/PostCategory/?id=categoryname
        public async Task<ActionResult> Index(string id)
        {
            ViewBag.Category = id;
            CategoryData cd = new CategoryData();
            HttpResponseMessage resp = await client.GetAsync("api/CategoryData/?$filter=title eq '" + id + "'");
            resp.EnsureSuccessStatusCode();

            cd = (await resp.Content.ReadAsAsync<IEnumerable<CategoryData>>()).FirstOrDefault();

            List<PostCategory> lpc = new List<PostCategory>();
            resp = await client.GetAsync("api/PostCategory/?$filter=categoryid eq " + cd.categoryid);
            resp.EnsureSuccessStatusCode();

            lpc = (await resp.Content.ReadAsAsync<IEnumerable<PostCategory>>()).ToList();

            List<PostEntry> lpe = new List<PostEntry>();
            foreach (PostCategory item in lpc){
                resp = await client.GetAsync("api/PostEntry/" + item.postid);
                resp.EnsureSuccessStatusCode();

                lpe.Add(await resp.Content.ReadAsAsync<PostEntry>());
            }

            return View(lpe);
        }
	}
}